package com.example.movie.ui.user.fragment

import android.graphics.Rect
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import com.dueeeke.videoplayer.util.L
import com.example.movie.data.user.factory.UserInfoPageViewModelFactory
import com.example.movie.data.user.model.UserInfoPageViewModel
import com.example.movie.ui.user.adapter.VideoRecyclerViewAdapter.VideoHolder

/**
 * 滑动列表自动播放，仅包含自动播放的逻辑
 */
open class RecyclerViewAutoPlayFragment : RecyclerViewFragment() {

    private val userInfoPageViewModel: UserInfoPageViewModel by viewModels(factoryProducer = { UserInfoPageViewModelFactory() })

    override fun initView() {
        super.initView()
        mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) { //滚动停止
                    autoPlayVideo(recyclerView)
                }
            }

            private fun autoPlayVideo(view: RecyclerView?) {
                if (view == null) return
                //遍历RecyclerView子控件,如果mPlayerContainer完全可见就开始播放
                val count = view.childCount
                L.d("ChildCount:$count")
                for (i in 0 until count) {
                    val itemView = view.getChildAt(i) ?: continue
                    val holder = itemView.tag as VideoHolder
                    val rect = Rect()
                    holder.mPlayerContainer.getLocalVisibleRect(rect)
                    val height = holder.mPlayerContainer.height
                    if (rect.top == 0 && rect.bottom == height) {
                        startPlay(holder.mPosition)
                        break
                    }
                }
            }
        })


    }

    override fun initData() {
        super.initData()
        userInfoPageViewModel.loadMyLikeMovieVideoList()
        userInfoPageViewModel.videoList.observe(viewLifecycleOwner){
            mVideos.addAll(it)
            mAdapter!!.notifyDataSetChanged()
            mRecyclerView.post {
                //自动播放第一个
                startPlay(0)
            }
        }

    }
}